package com.study.httpserver;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslContext;

public class ServerHandlerInit extends ChannelInitializer<SocketChannel> {

    private final SslContext sslContext;

    public ServerHandlerInit(SslContext sslContext) {
        this.sslContext = sslContext;
    }

    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // SSL的http请求handler
        if (sslContext != null) {
            pipeline.addLast(sslContext.newHandler(ch.alloc()));
        }
        pipeline.addLast("encode", new HttpResponseEncoder());
        pipeline.addLast("decode", new HttpRequestDecoder());
        pipeline.addLast("aggre", new HttpObjectAggregator(32 * 1024)); // 32M
        // 开启压缩
        pipeline.addLast("compressor", new HttpContentCompressor());
        pipeline.addLast("busi", new BusinessHandler()); // 业务处理
    }
}
